<template>
  <div class="home">
    <nav-bar class="home-nav">
      <div slot="center">购物街</div>
    </nav-bar>
    <tab-control
      :titles="['流行', '新款', '精选']"
      class="tab-control"
      @tabClick="tabClick"
      ref="tabControl1"
      v-show="isTabFixed"
    ></tab-control>
    <scroll
      class="content"
      ref="scroll"
      :probe-type="3"
      @scroll="contentScroll"
      :pull-up-load="true"
      @pullingUp="loadMore"
    >
      <home-swiper
        :banners="banners"
        @swiperImageLoad="swiperImageLoad"
      ></home-swiper>
      <recommend-view :recommends="recommends"></recommend-view>
      <feature-view></feature-view>
      <tab-control
        :titles="['流行', '新款', '精选']"
        @tabClick="tabClick"
        ref="tabControl2"
      ></tab-control>
      <goods-list :goods="showGoods"></goods-list>
    </scroll>
    <!-- <button @click="btnClick"></button>
    <div @click="divClick"></div>
    监听组件根元素的原生事件-->
    <back-top @click.native="backClick" v-show="isShowBackTop" />
  </div>
</template>

<script>
// import { Swiper, SwiperItem } from 'components/common/swiper/index'
import HomeSwiper from "./childComps/HomeSwiper";
import RecommendView from "./childComps/RecommendView";
import FeatureView from "./childComps/FeatureView";

import NavBar from "components/common/navbar/NavBar";
import TabControl from "components/content/tabControl/TabControl";
import GoodsList from "components/content/goods/GoodsList";
import Scroll from "components/common/scroll/Scroll";
import BackTop from "components/content/backTop/BackTop";

import { getHomeMultidata, getHomeGoods } from "network/home";
import { itemListenerMixin, backTopMixin } from "common/mixin";

export default {
  name: "Home",
  components: {
    HomeSwiper,
    RecommendView,
    FeatureView,
    NavBar,
    TabControl,
    GoodsList,
    Scroll,
    BackTop,
    // Swiper,
    // SwiperItem,
  },
  data() {
    return {
      // result: null
      banners: [],
      recommends: [],
      // 保存商品的数据结构设计
      goods: {
        pop: { page: 0, list: [] },
        new: { page: 0, list: [] },
        sell: { page: 0, list: [] },
      },
      currentType: "pop",
      // isShowBackTop: false,
      tabOffsetTop: 0,
      isTabFixed: false,
    };
  },
  mixins: [itemListenerMixin, backTopMixin],
  computed: {
    showGoods() {
      return this.goods[this.currentType].list;
    },
  },
  // 因为 home 是在有缓存的 keep-alive
  // 路由的两个声明周期
  // 进入页面的钩子
  activated() {
    this.$refs.scroll.scrollTo(0, this.saveY, 0);
    this.$refs.scroll.refresh();
  },
  // 销毁之前拿到 y 值
  // 离开页面时的钩子
  deactivated() {
    this.saveY = this.$refs.scroll.getScrollY();

    // 取消全局事件的监听，主要是 EventBus
    this.$bus.$off("itemImageLoad", this.itemImageListener);
  },
  created() {
    // 请求多个数据
    this.getHomeMultidata();

    // 请求商品数据
    this.getHomeGoods("pop");
    this.getHomeGoods("new");
    this.getHomeGoods("sell");

    // this.tabOffsetTop = this.$refs.tabControl.$el.offsetTop
  },
  mounted() {
    // 获取 tabControl 的 offsetTop
    // 所有的组件都有一个属性 $el，用于获取组件中的元素
    // 图片还没有加载完成
    // this.tabOffsetTop = this.$refs.tabControl.$el.offsetTop;
    // 闭包 refresh 是不会被销毁的
    // const refresh = debounce(this.$refs.scroll.refresh, 200);
    // 监听图片加载完成
    // Eventbus 事件通信
    //   this.itemImageListener = () => {
    //     refresh();
    //   }
    //   this.$bus.$on("itemImageLoad", this.itemImageListener);
  },
  methods: {
    // 防抖
    // debounce(func, delay) {
    //   let timer = null;
    //   return function (...args) {
    //     if (timer) clearTimeout(timer)
    //     timer = setTimeout(() => {
    //       func.apply(this, args)
    //     }, delay)
    //   }
    // },

    // 事件监听相关方法
    // 根据 index，设置 currentType，请求 currentType 类型的数据
    tabClick(index) {
      // console.log(index)
      switch (index) {
        case 0:
          this.currentType = "pop";
          break; // case 穿透
        case 1:
          this.currentType = "new";
          break;
        case 2:
          this.currentType = "sell";
          break; // 因为有 default
      }
      // 将 currentIndex 与最新点击的 index 保持一致
      // 因为不能保证用户点击的是哪一个 tabControl
      this.$refs.tabControl1.currentIndex = index;
      this.$refs.tabControl2.currentIndex = index;
    },

    // backClick() {
    //   console.log("被点击");
    //   this.$refs.scroll.scrollTo(0, 0);
    // },

    contentScroll(position) {
      // 1. 判断 BackTop 是否显示
      // this.isShowBackTop = -position.y > 1000;
      this.listenShowBackTop(position);

      // 2. 判断 tabControl 是否吸顶
      this.isTabFixed = -position.y > this.tabOffsetTop;
    },

    loadMore() {
      // 加载上拉加载更多
      this.getHomeGoods(this.currentType);
    },

    swiperImageLoad() {
      this.tabOffsetTop = this.$refs.tabControl2.$el.offsetTop;
    },

    // 网络请求相关方法
    // 请求多个数据
    getHomeMultidata() {
      getHomeMultidata().then((res) => {
        this.banners = res.data.banner.list;
        this.recommends = res.data.recommend.list;
      });
    },
    getHomeGoods(type) {
      const page = this.goods[type].page + 1;
      getHomeGoods(type, page).then((res) => {
        this.goods[type].list.push(...res.data.list);
        this.goods[type].page += 1;
        // 完成上拉加载更多
        this.$refs.scroll.finishPullUp();
      });
    },
  },
};
</script>

<style scoped>
.home {
  height: 100vh;
  padding-top: 44px;
  position: relative;
}

.home-nav {
  background-color: var(--color-tint);
  color: #fff;
  font-size: 16px;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  z-index: 9;
}

/*
.tab-control {
  当滚动到 44px 时，浏览器会自动将 position 转换为 flxed，position 在 static 和 fixed 来回切换
  position: sticky;
  top: 44px;
}

*/

.content {
  overflow: hidden;
  /* height: calc(100% - 93px);
  padding-top: 44px; */

  position: absolute;
  top: 44px;
  bottom: 49px;
  left: 0;
  right: 0;
}

.tab-control {
  position: relative;
  z-index: 9;
}

/* .fixed {
  position: fixed;
  left: 0;
  right: 0;
  top: 44px;
} */
</style>

// 函数调用 -> 压入函数栈（保存函数调用过程中所有变量）
// 函数调用结束 -> 弹出函数栈（释放函数所有的变量）
// 函数执行完之后，这些变量都不存在了，局部变量
// function test() {
//   const names = ['why', 'aaa']
// }
// test()
// 再调用一次，重新创建
// test()
